package com.genesis.yunnanji.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.RegisterBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import es.dmoral.toasty.Toasty;
import okhttp3.Call;



public class Register extends BaseActivity {
    @ViewInject(R.id.tb_register_toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.tv_register_getvcode)
    private TextView tvGetCode;
    @ViewInject(R.id.bt_register_reg)
    private Button btReg;
    @ViewInject(R.id.et_register_phone)
    private EditText etPhone;
    @ViewInject(R.id.et_register_vcode)
    private EditText etVcode;
    @ViewInject(R.id.et_register_password)
    private EditText etPwd;
    @ViewInject(R.id.et_register_password2)
    private EditText etPwd2;
    private String smstoken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_register);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void setUpView() {

    }

    @Event(value = {R.id.tv_register_getvcode, R.id.bt_register_reg}, type = View.OnClickListener.class)
    private void click(View v) {
        switch (v.getId()) {
            case R.id.tv_register_getvcode:
                if (TextUtils.isEmpty(etPhone.getText()) || etPhone.getText().toString().length() != 11) {
                    Toast.makeText(context, "请输入正确手机号", Toast.LENGTH_SHORT).show();
                } else {
                    getCode();
                }
                break;
            case R.id.bt_register_reg:
                if (!TextUtils.isEmpty(etPhone.getText().toString())
                        && !TextUtils.isEmpty(etVcode.getText().toString())
                        && !TextUtils.isEmpty(etPwd.getText().toString())
                        && !TextUtils.isEmpty(etPwd2.getText().toString())) {
                    Reg();
                }else{
                    Toasty.info(context, "请先完善资料！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void getCode() {
        String token = genesisUtils.getMD5Str(genesisUtils.sortNum(etPhone.getText().toString() + GenesisApiConfig.TOKEN_STR));
        OkHttpUtils
                .post()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.GET_VCODE)
                .addParams("mobile", etPhone.getText().toString())
                .addParams("token", token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        RegisterBean registerBean = gson.fromJson(response, RegisterBean.class);
                        if (registerBean.getStatus() == 200) {
                            smstoken = registerBean.getResult().getSmstoken();
                            Toast.makeText(context, registerBean.getMessage(), Toast.LENGTH_SHORT).show();
                            Message message = handler.obtainMessage(1);     // Message
                            handler.sendMessageDelayed(message, 1000);
                        } else {
                            Toast.makeText(context, registerBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    int recLen = 180;
    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    recLen--;
                    tvGetCode.setText(recLen + "S");

                    if (recLen > 0) {
                        Message message = handler.obtainMessage(1);
                        handler.sendMessageDelayed(message, 1000);      // send message
                        tvGetCode.setClickable(false);
                    } else {
                        tvGetCode.setClickable(true);
                        tvGetCode.setText("获取");
                    }
            }

            super.handleMessage(msg);
        }
    };




    public void Reg() {
        OkHttpUtils
                .post()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.REG)
                .addParams("mobile", etPhone.getText().toString())
                .addParams("smscode", genesisUtils.getMD5Str(etVcode.getText().toString()))
                .addParams("smstoken", smstoken)
                .addParams("upwd", etPwd.getText().toString())
                .addParams("urpwd", etPwd2.getText().toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if (jsonObject.optInt("status") == 200) {
                                Toasty.success(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toasty.error(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                });
    }

}
